package edu.ou.herbarium.threads2;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.util.ArrayList;

import edu.ou.herbarium.sharedata.ErrorData;
import edu.ou.herbarium.sharedata.ShareData1;
import edu.ou.herbarium.sharedata.ShareData2;
import edu.ou.herbarium.sharedata.TransferData1;
import edu.ou.herbarium.threads.ShareData;
import edu.ou.herbarium.wsclient.Specimen;

public class ClientThread extends Thread{
	private Socket connectionSocket = null;
	private ShareData1 s1;
	private ShareData2 s2;
	private ErrorData de;
	private int clientId;
	private int spanCounter = 0;//**INFO_CLIENT_100
	
	public ClientThread(ShareData1 s1, Socket socket, ErrorData de, Integer clientId) {
		this.setConnectionSocket(socket);
		this.s1 = s1;
		this.setS2(new ShareData2());
		this.de = de;
		this.clientId = clientId;
	}
	public void run(){
		String clientSentence;
		int index2 = 0;
		try {
			BufferedReader inFromClient = new BufferedReader(
					new InputStreamReader(getConnectionSocket().getInputStream()));
			DataOutputStream outToClient = new DataOutputStream(
					getConnectionSocket().getOutputStream());
			DatagramSocket dsocket2 = new DatagramSocket();
			
			while (true) {
				clientSentence = inFromClient.readLine();
				ArrayList<DataItem> itemlist = new ArrayList<DataItem>();
				if(clientSentence==null||clientSentence.equals("")){
					System.out.println("empty");
					continue;
				}
				else if (clientSentence.equals("BYE"))
				{
					if(spanCounter==ShareData.TIME_SPAN){
						System.out.println("data loader exit");
						s1.setShareData(new TransferData1(null,getS2()));
						outToClient.close();
						inFromClient.close();
						getConnectionSocket().close();
						
						de.setShareData("INFO_CLIENT_"+(1000+clientId)+"::"+"_");
						return;
					} 
					s1.setShareData(new TransferData1(null,getS2()));
					spanCounter++;
					continue;
				}
				else if(clientSentence.startsWith("Username")){
					outToClient.writeChars("16");
					continue;
				}
				else{
					String items[] = clientSentence.split(",");
					System.out.println(clientSentence);
					for(int index = 0;index<items.length;index++){
						String item = items[index];
						item = item.replace("{", "");
						item = item.replace("}", "");
						if(item.equals("#")==false){
							DataItem di = new DataItem(item.split(":")[0].replaceAll("\"", ""),item.split(":")[1].replaceAll("\"", ""));
							System.out.println("123123"+item.split(":")[0].replaceAll("\"", "")+" "+item.split(":")[1].replaceAll("\"",""));
							itemlist.add(di);
						}
					}
				}
				String [] dataArray = clientSentence.split(",");
				Specimen spec = new Specimen();
				
				System.out.println("start="+System.currentTimeMillis());
				
				
				System.out.println("Fol="+getData(itemlist,"Fol"));
				spec.setBarcode(getData(itemlist,"Barcode"));
				System.out.println(getData(itemlist,"Barcode"));
				spec.setTempData(getData(itemlist,"cl"));
				System.out.println(getData(itemlist,"cl"));
				spec.setStateProvince(getData(itemlist,"st"));
				System.out.println(getData(itemlist,"st"));
				spec.setTown(getData(itemlist,"Town"));
				System.out.println(getData(itemlist,"Town"));
				spec.setWatermark("QRCODE_"+index2);
				System.out.println("QRCODE_"+index2);
				spec.setCounty(getData(itemlist,"ct"));
				System.out.println(getData(itemlist,"ct"));
				spec.setGenus(getData(itemlist,"g"));
				System.out.println(getData(itemlist,"g"));
				spec.setFamily(getData(itemlist,"ir"));
				System.out.println(getData(itemlist,"ir"));
				spec.setSpecificEpithet(getData(itemlist,"i"));
				System.out.println(getData(itemlist,"i"));
				spec.setCountry("United States");
				spec.setDarwinCountry("United States");
				spec.setSheetNotes("This is a test sheet note.");
				spec.setScientificName(getData(itemlist,"sn"));
				
				
				String host2 = "localhost";
				int port2 = 60011;
				byte[] message2 = "conveyor".getBytes();

				InetAddress address2 = InetAddress.getByName(host2);
				DatagramPacket packet2 = new DatagramPacket(message2,
						message2.length, address2, port2);
				
				dsocket2.send(packet2);
				
				Thread.sleep(3000);
//				byte[] receiveData2 = new byte[1024];
//				for (int i = 0; i < receiveData2.length; i++)
//					receiveData2[i] = 0;
//				DatagramPacket receivePacket2 = new DatagramPacket(receiveData2,
//						receiveData2.length);
//				serverSocket2.receive(receivePacket2);
//				String sentence = new String(receivePacket2.getData());
				if(getData(itemlist,"Fol").equals("0"))
					s1.setShareData(new TransferData1(spec,getS2()));
				else index2++;
			}
		}catch (Exception e){
			e.printStackTrace();
		}
	}
	
	public String getData(ArrayList<DataItem> items, String title){
		String result = "";
		for(int i=0;i<items.size();i++){
			if(items.get(i).getName().equals(title)){
				result = items.get(i).getData();
				break;
			}
		}
		return result;
	}
	public Socket getConnectionSocket() {
		return connectionSocket;
	}
	public void setConnectionSocket(Socket connectionSocket) {
		this.connectionSocket = connectionSocket;
	}
	public ShareData2 getS2() {
		return s2;
	}
	public void setS2(ShareData2 s2) {
		this.s2 = s2;
	}
}

class DataItem {

	String name = "";
	String data = "";
	public DataItem(String name, String data) {
		super();
		this.name = name;
		this.data = data;
	}
	
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getData() {
		return data;
	}
	public void setData(String data) {
		this.data = data;
	}
} 
